// 通用接口
const mongoose = require('mongoose');
const User = require("../models/User/User");
const Maps = require("../models/Map");
const Npc = require("../models/Npc/Npc");

exports.getUserInfo = async (req, res) => {
    let uid;
    let name = req.user.name
    let myInfo;
    if (!name) {
        return res.json({ code: 0, msg: "name error", data: null })
    }
    if (name && name.length > 10) {
        myInfo = await User.findById(uid)
    } else {
        await User.findOne({ name: name }).populate(
            'now_map', 'name').exec((err,info) => {
            if(err)return res.status(404).json(err);
            if(!info){
                return res.status(404).json('没有角色信息');
            }
            return res.json(info);
        });
    }
}
// 获得玩家锻炼数据
exports.getUserGymInfo = async (req, res) => {
    let uid;
    let name = req.user.name
    let myInfo;
    if (!name) {
        return res.json({ code: 0, msg: "name error", data: null })
    }
    if (name && name.length > 10) {
        myInfo = await User.findById(uid)
    } else {
        myInfo = await User.findOne({ name: name });
    }
    gymmsg = {
        strength: myInfo.strength,
        defense: myInfo.defense,
        magic: myInfo.magic,
        speed: myInfo.speed
    };
    return res.json(gymmsg);
};

exports.getMapInfo = async (req, res) => {
    let mapInfo = await Maps.find({});
    newmapinfo = mapInfo;
    return res.json(newmapinfo);
};

exports.getPlayerInfo = async (req, res) => {
    // 用mid去拿地图的所有角色信息（NPC、玩家）
    let mid = req.params.id
    if (!mid) {
        return res.json({ code: 0, msg: "缺少地图id参数", data: null })
    }else{
        let map = await Maps.findOne({ _id: mid });
        let id = map._id.toString();
        let Userlist = await User.find({ now_map:id }).select('_id name hp user_exp status now_map').populate(
            'now_map', 'name');
        let Npclist = await Npc.find({ now_map:id }).select('_id name hp user_exp status now_map').populate(
            'now_map', 'name');
        await Userlist.push.apply(Userlist,Npclist); // 合并返回的数组
        return res.json(Userlist);
    }
};


